package com.lagou.cl.encode;

import com.lagou.cl.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author 程  林
 * @date 2020-05-24 17:19
 * @description // 自定义RPC解码器
 * @since V1.0.0
 */
public class RpcDecoder extends ByteToMessageDecoder {

	private Class<?> clazz;

	private Serializer serializer;

	public RpcDecoder(Class<?> clazz, Serializer serializer) {
		this.clazz = clazz;
		this.serializer = serializer;
	}

	@Override
	protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

		if (null != byteBuf) {
			//在byteBuf缓冲区中标记当前的索引
			byteBuf.markReaderIndex();
			//在当前索引处获取
			int length = byteBuf.readableBytes();

			//创建一个初始化字节数据
			byte[] msg = new byte[length];

			//从当前{@code readerIndex}开始将该缓冲区的数据传输到指定的目标，并通过传输的字节数（= {@code dst.length}）增加{@code readerIndex}
			byteBuf.readBytes(msg,byteBuf.readerIndex(),length);

			//反序列化
			list.add(serializer.deserialize(clazz, msg));
		}
	}
}
